package org.example.aienglishapp.controller.article;

import org.example.aienglishapp.dto.article.ArticleDTO;
import org.example.aienglishapp.service.article.ArticleService;
import org.example.aienglishapp.config.others.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisService redisService;  // 注入 RedisService

    @PostMapping("/add")
    public ResponseEntity<?> addNewArticle(@RequestBody ArticleDTO articleDTO) {
        try {
            articleService.addNewArticle(articleDTO); // 调用保存文章的方法

            // 将文章存入 Redis
            redisService.set("article:" + articleDTO.getArticleId(), articleDTO); // 将文章添加到 Redis

            return ResponseEntity.ok().body(Map.of("articleId", articleDTO.getArticleId())); // 返回文章ID
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error adding article");
        }
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<ArticleDTO> getArticleById(@PathVariable Long id) {
        // 先从 Redis 获取文章
        ArticleDTO articleDTO = (ArticleDTO) redisService.get("article:" + id);

        if (articleDTO == null) {
            // 如果 Redis 中没有，从数据库中获取
            articleDTO = articleService.getArticleById(id);

            // 如果从数据库获取到，更新 Redis
            if (articleDTO != null) {
                redisService.set("article:" + id, articleDTO);
            }
        }

        if (articleDTO == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);  // 如果没有找到文章
        }

        return ResponseEntity.ok(articleDTO);
    }

    @GetMapping()
    public ResponseEntity<List<ArticleDTO>> getAllArticles() {
        List<ArticleDTO> articles = articleService.getAllArticles();
        return ResponseEntity.ok(articles);
    }

    @PutMapping("/update/{id}")
    public ResponseEntity<Void> updateArticle(@PathVariable Long id, @RequestBody ArticleDTO articleDTO) {
        articleDTO.setArticleId(id); // 确保 ID 一致
        articleService.updateArticle(articleDTO);

        // 更新 Redis 中的缓存
        redisService.set("article:" + id, articleDTO);

        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Void> deleteArticle(@PathVariable Long id) {
        articleService.deleteArticle(id);

        // 删除 Redis 中的缓存
        redisService.delete("article:" + id);

        return ResponseEntity.ok().build();
    }
}